/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.servlets.validation;

import com.codemagi.servlets.AppException;
import com.codemagi.util.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;


/**
 * Throws an exception if the passed email address (String) domain is not emailDomain from the LoginController init param.
 */
public class EmailAddressDomainValidator implements IValidator {

    protected static final String MSG_INVALID_DOMAIN = "The email address entered is not in a valid domain.";

    private String[] validDomains;
    private List<Pattern> patterns;

    public EmailAddressDomainValidator(String domain) {
        validDomains = new String[1];
	validDomains[0] = domain;

	compilePatterns();
    }

    public EmailAddressDomainValidator(String[] domains) {
        validDomains = domains;

	compilePatterns();
    }

    public Object validate(Object obj, HttpServletRequest request) throws AppException {

	if (obj instanceof String) {
	    
	    String output = (String)obj;

	    if ( !Utils.isEmpty(output) ) {

		//cleanup the entered code
		output = StringUtils.trim(output);

		//iterate the valid email domains and make sure the passed email contains at least one
		boolean isValidDomain = false; 
		for (Pattern p : patterns) {
		    Matcher m = p.matcher(output);

		    if ( m.find() ) return output;
		}

		//the passed email did not match any valid domain
		throw new AppException( MSG_INVALID_DOMAIN );

	    }
	}

	return obj;
    }

    private void compilePatterns() {
	patterns = new ArrayList<Pattern>(validDomains.length);

	for (String domain : validDomains) {
	    Pattern p = Pattern.compile("@" + domain + "\\z", Pattern.CASE_INSENSITIVE);
	    patterns.add(p);
	}
    }

}
